<?php

namespace app\api\controller;

use addons\shopro\model\Order;
use addons\shopro\model\OrderItem;
use app\admin\model\ClincActivity;
use app\admin\model\ClincScore;
use app\admin\model\ClinicLog;
use app\common\controller\Api;
use app\common\model\MoneyLog;
use app\common\model\User;
use think\Db;
use think\Exception;
use think\Validate;
use addons\shopro\library\traits\model\order\OrderOper;
/**
 * 门诊店接口
 */
class Clinc extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['clinc_list','clinc_detail','doctor_list'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];


    /**
     * 当前活动 就诊记录
     */
    public function clinic_log()
    {
        //$type = $this->request->param('type',1); //就诊类型
        $clinc_activity_id = $this->request->param('clinc_activity_id');    //活动ID
        $clinic_log = ClinicLog::with(['user'])->where(['clinc_activity_id'=>$clinc_activity_id])->paginate()->each(function($row){
        $row->mobile =substr_replace($row->mobile,'****',3,4);
        $row->name = substr_cut($row->name);
        $row->avatar = isset($row->user->avatar)?$row->user->avatar:'';
        $row->hidden(['user']);
        });
        $this->success('获取成功',$clinic_log);
    }

    /**
     * 活动报名
     */
    public function activity_baoming()
    {
        $name = input('name');//姓名
        $mobile = input('mobile');//手机号
        //$doctor_id = $this->request->post('doctor_id');//医生ID
        $clinc_activity_id = (int)input('clinc_activity_id'); //活动ID
        if (strlen($mobile) != 11) {
            $this->error(__('Mobile is incorrect'));
        }
        if(empty($name)){
            $this->error('姓名不能为空');
        }
//        if(empty($doctor_id)){
//            $this->error('请输入医生ID');
//        }
        $clinc_activity = ClincActivity::where(['id'=>$clinc_activity_id])->find();
        if(!$clinc_activity){
            $this->error('未找到门诊活动');
        }
//        $doctor_arr = explode(',',$clinc_activity['doctor_ids']);
//        if(!in_array($doctor_id,$doctor_arr)){
//            $this->error('选择医生异常');
//        }
        if(!$clinc_activity){
            $this->error('当前活动有误');
        }
        if($clinc_activity['status']==0){
            $this->error('当前活动已经停止');
        }
//        if($this->auth->money<$clinc_activity->price){
//            $this->error('余额不足');
//        }
        $exists = ClinicLog::where(['user_id'=>$this->auth->id,'clinc_score_id'=>$clinc_activity->clinc_score_id,'clinc_activity_id'=>$clinc_activity_id])->count();
        if($exists){
            $this->error('当前活动已经报名过');
        }
        Db::startTrans();
        try {
            //减去余额
            //User::money(-$clinc_activity->price,$this->auth->id,'活动报名');

            //生成订单
            $order_sn = OrderOper::getSn($this->auth->id);
            $newOrder = [];
            $newOrder['clinc_score_id'] = $clinc_activity->clinc_score_id;
            $newOrder['type'] = 'goods';
            $newOrder['order_sn'] = $order_sn;
            $newOrder['user_id'] = $this->auth->id;
            $newOrder['order_type'] = 'goods';
            $newOrder['activity_type'] = 'activity_baoming';
            $newOrder['goods_amount'] = $clinc_activity->price;
            $newOrder['phone'] = $mobile;
            $newOrder['total_amount'] = $clinc_activity->price;
            $newOrder['total_fee'] = $clinc_activity->price;
            $newOrder['pay_fee'] = $clinc_activity->price;
            $newOrder['pay_fee'] = $clinc_activity->price;
            $newOrder['status'] = 0;
            $newOrder['remark'] = '门诊店活动报名';
            $newOrder['platform'] = request()->header('platform');
            $order = new Order();
            $order->allowField(true)->save($newOrder);

            //添加订单item
            $orderItem = new OrderItem();
            $orderItem->user_id = $this->auth->id;
            $orderItem->order_id = $order->id;
            $orderItem->goods_id = $clinc_activity_id;//报名的活动ID
            $orderItem->activity_type = '门诊店活动报名';
            $orderItem->goods_title = $clinc_activity->clinc_theme;
            $orderItem->goods_num = 1;
            $orderItem->goods_original_price = $clinc_activity->price;
            $orderItem->goods_price = $clinc_activity->price;
            $orderItem->pay_price = $clinc_activity->price;
            $orderItem->aftersale_status = 0;
            $orderItem->createtime = time();
            $orderItem->comment_status = 0;
            $orderItem->save();
            //就诊记录
            $clinic_log = [
                'user_id'   =>  $this->auth->id,
                'clinc_score_id'    =>  $clinc_activity->clinc_score_id,
                'clinc_activity_id' =>  $clinc_activity_id,
                'order_sn' =>  $order_sn,
                'name'      =>  $name,
                'mobile'    =>  $mobile,
                'sex'       =>  $this->auth->gender,
                'status'    =>  0,
                //'doctor_id' =>  $doctor_id,
                'price' =>  $clinc_activity->price,
                'ctime'     =>  time()
            ];
            Db::name('clinic_log')->insert($clinic_log);
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            $this->error('系统异常'.$e->getMessage().'行='.$e->getLine());
        }
        $this->success('报名成功',['order_sn'=>$order_sn]);
    }



    /**
     * 门诊店列表
     */
    public function clinc_list()
    {
        $clinc_list = ClincScore::where(['status'=>1])->paginate();
        $this->success('获取成功',$clinc_list);
    }

    /**
     * 门诊店详情
     */
    public function clinc_detail()
    {
        $clinc_score_id = $this->request->param('clinc_score_id');
        //
        $clinc_detail = \app\admin\model\shopro\store\Store::with(['clincactivity'])->where(['id'=>$clinc_score_id,'status'=>1])->find();
        $this->success('门诊店详情',$clinc_detail);
    }

    /**
     *活动对应的医生列表
     */
    public function doctor_list()
    {
        //先检查活动是否是开启状态
       $clinc_activity_id = $this->request->param('clinc_activity_id');
       if(empty($clinc_activity_id)){
           $this->error('请输入门诊活动ID');
       }
       $clinc_activity = ClincActivity::where(['id'=>$clinc_activity_id])->find();
       if(!$clinc_activity){
           $this->error('参数有误，未找到相关活动');
       }
       if($clinc_activity['status']==0){
           $this->error('当前活动未开启');
       }
       //->where(['clinc_score_id'=>$clinc_activity->clinc_score_id])
       $doctor_list = \app\admin\model\Doctor::whereIn('id',$clinc_activity['doctor_ids'])->select();
       if($doctor_list){
           foreach ($doctor_list as $k=>&$v){
               $v->goodat = strip_tags($v->goodat);
               $v->department = Db::name('category')->where(['type'=>'department','id'=>$v->department_id])->value('name')??'';
           }
       }
       $this->success('ok',$doctor_list);
    }
}
